package com.sky.server.impl;

import com.sky.dto.DataQueryDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.ReportMapper1;
import com.sky.server.ReportService1;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl1 implements ReportService1 {
    @Autowired
    private ReportMapper1 reportMapper1;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public SalesTop10ReportVO selectTop10(String begin, String end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        List<String> strings1 = null;
        List<String> strings2 = null;

        if (end == null) {
            throw new BaseException("传入的截止日期不能为空");
        }

        if (end.equals(begin)) {
            strings1 = reportMapper1.selectTop10NameDay(begin, end);
            strings2 = reportMapper1.selectTop10NumberDay(begin, end);
        } else {
            strings1 = reportMapper1.selectTop10NameDays(begin, end);
            strings2 = reportMapper1.selectTop10NumberDays(begin, end);
        }

        salesTop10ReportVO.setNameList(StringUtils.strip(strings1.toString(), "[]"));

        salesTop10ReportVO.setNumberList(StringUtils.strip(strings2.toString(), "[]"));

        return salesTop10ReportVO;
    }

    @Override
    public UserReportVO selectUserStatistics(String begin, String end) {
        UserReportVO userReportVO = new UserReportVO();
        List<String> strings1 = new ArrayList<>();
        List<String> strings2 = new ArrayList<>();
        List<String> strings3 = new ArrayList<>();
        if (end == null) {
            throw new BaseException("传入的截止日期不能为空");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(begin, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);
        log.info("{}", startDate);
        log.info("{}", endDate);
        while (!startDate.isAfter(endDate)) {
            log.info("{}", startDate);
            strings1.add(reportMapper1.selectUserStatisticNew(startDate.format(formatter)));
            strings2.add(reportMapper1.selectUserStatisticsAll(startDate.format(formatter)));

            strings3.add(String.valueOf(startDate).substring(5));
            startDate = startDate.plusDays(1);

        }

        userReportVO.setNewUserList(StringUtils.strip(strings1.toString(), "[]"));
        userReportVO.setTotalUserList(StringUtils.strip(strings2.toString(), "[]"));
        userReportVO.setDateList(StringUtils.strip(strings3.toString(), "[]"));
        return userReportVO;
    }

    @Override
    public void getExport(HttpServletResponse response) {
        //查询最近30天营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        DataQueryDTO dataQueryDTO = new DataQueryDTO();
        dataQueryDTO.setBegin(String.valueOf(dateBegin));
        dataQueryDTO.setEnd(String.valueOf(dateEnd));

        //将数据写入Excel文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/repot.xlsx");
        try {
            XSSFWorkbook sheets = new XSSFWorkbook(resourceAsStream);
            XSSFSheet sheetAt = sheets.getSheet("Sheet1");
            sheetAt.getRow(1).getCell(1).setCellValue("统计时间: " + dateBegin + "至" + dateEnd);
            BigDecimal allBusinessAmount1 = reportMapper1.getAllBusinessAmount(dataQueryDTO);
            if (allBusinessAmount1 == null) {


                allBusinessAmount1 = BigDecimal.valueOf(0);
            }
            XSSFRow row = sheetAt.getRow(3);
            row.getCell(2).setCellValue(allBusinessAmount1 + "");

//                    .setCellValue(reportMapper1.getAllBusinessAmount(dataQueryDTO));

            Integer totalOrderCount = reportMapper.getTotalOrderCount(dataQueryDTO);
            Integer validOrderCount = reportMapper.getTotalValidOrderCount(dataQueryDTO);
            BigDecimal orderCompletionRate;
            if (0 == totalOrderCount) {
                orderCompletionRate = BigDecimal.valueOf(0);
            } else {
                orderCompletionRate = BigDecimal.valueOf(validOrderCount).divide(BigDecimal.valueOf(totalOrderCount), 2, RoundingMode.HALF_UP);
            }

            row.getCell(4).setCellValue((orderCompletionRate.divide(BigDecimal.valueOf(0.01), 0, RoundingMode.DOWN)) + "%");
            row.getCell(6).setCellValue(reportMapper1.selectUserStatisticsAll(String.valueOf(dateEnd)));

            XSSFRow row1 = sheetAt.getRow(4);
            row1.getCell(2).setCellValue(orderMapper.activeOrderCount30(dataQueryDTO));
            BigDecimal allBusinessAmount = reportMapper1.getAllBusinessAmount(dataQueryDTO);
            Integer orderCount30 = orderMapper.activeOrderCount30(dataQueryDTO);
            row1.getCell(4).setCellValue(allBusinessAmount.divide(BigDecimal.valueOf(orderCount30), 2, RoundingMode.DOWN) + "");

            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //获取行数
                XSSFRow row2 = sheetAt.getRow(7 + i);
                row2.getCell(1).setCellValue(date.toString());
                BigDecimal sumAmount = reportMapper.getSumAmount(date.toString());
                if (sumAmount == null) {
                    sumAmount = BigDecimal.valueOf(0);
                }
                row2.getCell(2).setCellValue(sumAmount + "");

                row2.getCell(3).setCellValue(orderMapper.activeOrderCount(date.toString()));
                Integer activeOrderCount = orderMapper.activeOrderCount(date.toString());

                Integer orderCount = orderMapper.allOrder(date.toString());
                if (orderCount.equals(0)) {
                    orderCount = Integer.valueOf(1);
                }
                //完成率
                BigDecimal multiply = (BigDecimal.valueOf(activeOrderCount).divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.DOWN)).multiply(BigDecimal.valueOf(100));
                row2.getCell(4).setCellValue( multiply+ "%");
                if (activeOrderCount != 0) {
                    row2.getCell(5).setCellValue(sumAmount.divide(BigDecimal.valueOf(activeOrderCount), 2, RoundingMode.DOWN) + "");
                }
                row2.getCell(5).setCellValue(0);
                row2.getCell(6).setCellValue(reportMapper1.selectUserStatisticNew(date.toString()));
            }
            //3.输出文件
            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);
            outputStream.close();
            sheets.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
